package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Enumeration;
import java.util.ResourceBundle;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 王可
 * @Date: 2021/01/25/17:50
 * @Description: admin网关的全局过滤器
 */
@Component
@Log4j2
@Order(0)
public class AuthorizeFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request
        ServerHttpRequest request = exchange.getRequest();
        ///获取response
        ServerHttpResponse response = exchange.getResponse();

        //从login的配置文件中加载需要放行的请求路径
        ResourceBundle resourceBundle = ResourceBundle.getBundle("address");
        Enumeration<String> keys = resourceBundle.getKeys();

        while (keys.hasMoreElements()){
            try {
                String address = resourceBundle.getString(keys.nextElement());
                System.out.println(address);
                //判断请求的路径是否包含放行的路径
                if(request.getURI().getPath().contains(address)){
                    //包含放行的路径就放行。此处为登录等需要放行的路径
                    return chain.filter(exchange);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //获取请求头的jwt信息
        String jwtToken = request.getHeaders().getFirst("token");

        //判断当前令牌是否存在
        if(StringUtils.isEmpty(jwtToken)){
            //不存在返回错误信息,为授权登录
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            //携带有token信息，解析token信息，判断令牌信息是否合法，不合法则向客户端返会错误信息
            //加载载荷的body信息
            Claims claims = AppJwtUtil.getClaimsBody(jwtToken);

            //判断信息是否合法
            int i = AppJwtUtil.verifyToken(claims);
            if(i == 0 || i == -1){
               //令牌有效，重新向header中设置userId
                //获取载荷body中的id信息
                Integer id = (Integer) claims.get("id");
                //打印数据查看
                log.info("find userId:{} from uri:{}",id,request.getURI());

                //重新设置userId
                ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                    httpHeaders.add("id", String.valueOf(id));
                }).build();

                exchange.mutate().request(serverHttpRequest).build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //想客户端返回错误信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //一切顺利，放行
        return chain.filter(exchange);
    }
}
